import { useEffect, useRef, useState, useMemo } from "react"
import { ResponsiveObserver, responsiveArray, isObject } from "@/utils"
function isResponsiveValue(value) {
    return isObject(value)
}
const useResponsiveState = (val, defaultValue, fallbackToXs = false) => {
    const token = useRef("")
    const [screens, setScreens] = useState({
        sx: true,
        sm: true,
        md: true,
        lg: true,
        xl: true,
        xxl: true,
        xxxl: true
    })
    useEffect(() => {
        token.current = ResponsiveObserver.subscribe((screens) => {
            if (isResponsiveValue(val)) {
                setScreens(screens)
            }
        })
        return () => {
            ResponsiveObserver.unsubscribe(token.current)
        }
    }, [])
    const result = useMemo(() => {
        let res = defaultValue
        if (isResponsiveValue(val)) {
            for (let i = 0; i < responsiveArray.length; i++) {
                const breakpoint = responsiveArray[i]
                if ((screens[breakpoint] || breakpoint === "xs" && fallbackToXs) && val[breakpoint] != null) {
                    res = val[breakpoint]
                    break
                }
            }
        } else {
            res = val
        }
        return res
    }, [screens, val, defaultValue, fallbackToXs])
    return result
}
export default useResponsiveState